#!/bin/zsh -Ndefgku
#
# Scripts/package
# mas
#
# Copyright © 2025 mas-cli. All rights reserved.
#
# Builds .pkg installer.
#

. "${0:A:h}/_setup_script"

print_notice '📦 Packaging installer for' "${@}"

export MAS_DO_NOT_PRINT_NOTICE=
Scripts/build "${1:-}" -c release "${@:2}"
unset MAS_DO_NOT_PRINT_NOTICE

readonly build_folder=.build
readonly destination_folder="${build_folder}/destination"
readonly installation_folder=/usr/local/opt/mas
readonly installation_staging_folder="${destination_folder}${installation_folder}"
readonly usr_local_bin_staging_folder="${destination_folder}/usr/local/bin"
version="$(Scripts/version)"
readonly version

swift package generate-manual

mkdir -p "${installation_staging_folder}/bin"
mkdir -p "${installation_staging_folder}/etc/bash_completion.d"
mkdir -p "${installation_staging_folder}/share/fish/vendor_completions.d"
mkdir -p "${installation_staging_folder}/share/man/man1"
mkdir -p "${usr_local_bin_staging_folder}"

cp LICENSE README.md "${installation_staging_folder}"
cp contrib/completion/mas-completion.bash "${installation_staging_folder}/etc/bash_completion.d/mas"
cp contrib/completion/mas.fish "${installation_staging_folder}/share/fish/vendor_completions.d/mas.fish"
ln -f "$(swift build -c release --show-bin-path "${@:2}")/mas" "${installation_staging_folder}/bin/mas"
ln -f .build/plugins/GenerateManual/outputs/mas/mas.1 "${installation_staging_folder}/share/man/man1/mas.1"

ln -fs "${installation_folder}/bin/mas" "${usr_local_bin_staging_folder}/mas"

pkgbuild\
 --identifier io.github.mas-cli.mas\
 --install-location /\
 --version "${version}"\
 --root "${destination_folder}"\
 "${build_folder}/mas_components.pkg"

# shellcheck disable=SC1036
productbuild\
 --distribution =(<<< $'<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<installer-gui-script minSpecVersion="2">
	<title>mas</title>
	<pkg-ref id="io.github.mas-cli.mas">
		<bundle-version/>
	</pkg-ref>
	<pkg-ref id="io.github.mas-cli.mas" onConclusion="none">#mas_components.pkg</pkg-ref>
	<domains enable_localSystem="true" enable_anywhere="true" enable_currentUserHome="false"/>
	<options customize="never" require-scripts="false"/>
	<volume-check>
		<allowed-os-versions>
			<os-version min="10.15"/>
		</allowed-os-versions>
	</volume-check>
	<choices-outline>
		<line choice="default">
			<line choice="io.github.mas-cli.mas"/>
		</line>
	</choices-outline>
	<choice id="default"/>
	<choice id="io.github.mas-cli.mas" visible="false">
		<pkg-ref id="io.github.mas-cli.mas"/>
	</choice>
</installer-gui-script>
')\
 --package-path "${build_folder}"\
 "${build_folder}/mas-${version//\//_}-${${(s: :o)$(lipo -archs "${installation_staging_folder}/bin/mas")}// /-}.pkg"
